package com.tanhua.server.service;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.pojo.BlackList;
import com.tanhua.common.pojo.Settings;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.UserLike;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyCenterService {
    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;
    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RecommendUserService recommendUserService;
    @Autowired
    private IMService imService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private SettingsService settingsService;
    @Autowired
    private TanHuaService tanHuaService;
    @Autowired
    private BlackListService blackListService;


    /**
     * 根据⽤户id查询⽤户信息
     *
     * @param userId ⽤户id，如果为空，表示查询当前登录⼈的信息
     * @return
     */
    public UserInfoVo queryUserInfoByUserId(Long userId) {
        if (ObjectUtil.isEmpty(userId)) {
            // 没有传入数据，表示查询当前用户信息
            userId = UserThreadLocal.get().getId();
        }

        // 查询用户信息
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(userId);
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }

        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class, "marriage");
        userInfoVo.setGender(userInfo.getSex().toString().toLowerCase());
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
        return userInfoVo;
    }


    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     *
     * @return
     */
    public CountsVo queryCounts() {
        User user = UserThreadLocal.get();
        Long mutualLikeCount = this.userLikeApi.queryMutualLikeCount(user.getId());
        Long likeCount = this.userLikeApi.queryLikeCount(user.getId());
        Long fanCount = this.userLikeApi.queryFanCount(user.getId());

        CountsVo countsVo = new CountsVo();
        countsVo.setEachLoveCount(mutualLikeCount);
        countsVo.setLoveCount(likeCount);
        countsVo.setFanCount(fanCount);

        return countsVo;
    }

    /**
     * 互相关注、我关注、粉丝、谁看过我 - 翻页列表
     *
     * @param type     1 互相关注 2 我关注 3 粉丝 4 谁看过我
     * @param page     当前页
     * @param pageSize 页大小
     * @param nickname 昵称
     * @return
     */
    public PageResult queryLikeList(Integer type, Integer page, Integer pageSize, String nickname) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        Long userId = UserThreadLocal.get().getId();

        List<Object> userIdList = null;
        switch (type) {
            case 1: { // 1 互相关注
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryMutualLikeList(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "likeUserId");
                break;
            }
            case 2: { // 2 我关注
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryLikeList(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "likeUserId");
                break;
            }
            case 3: { // 3 粉丝
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryFanList(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "userId");
                break;
            }
            case 4: { // 4 谁看过我
                PageInfo<Visitors> visitorsPageInfo = this.visitorsApi.topVisitor(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(visitorsPageInfo.getRecords(), "visitorUserId");
                break;
            }
            default:
                return pageResult;
        }

        if (CollUtil.isEmpty(userIdList)) {
            return pageResult;
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIdList);
        if (StrUtil.isNotEmpty(nickname)) {
            queryWrapper.eq("nick_name", nickname);
        }

        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByQueryWrapper(queryWrapper);
        List<UserLikeListVo> userLikeListVos = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            UserLikeListVo userLikeListVo = new UserLikeListVo();
            userLikeListVo.setAge(userInfo.getAge());
            userLikeListVo.setAvatar(userInfo.getLogo());
            userLikeListVo.setCity(userInfo.getCity());
            userLikeListVo.setEducation(userInfo.getEdu());
            userLikeListVo.setGender(userInfo.getSex().name().toLowerCase());
            userLikeListVo.setId(userInfo.getUserId());
            userLikeListVo.setMarriage(StringUtils.equals(userInfo.getMarriage(), "已婚") ? 1 : 0);
            userLikeListVo.setNickname(userInfo.getNickName());

            if (type != 1) {
                //是否喜欢  userLikeApi中的isLike开放出来
                userLikeListVo.setAlreadyLove(this.userLikeApi.isLike(userId, userInfo.getUserId()));
            }

            if (type == 4) {
                Long score = this.recommendUserService.queryScore(userId, userInfo.getUserId());
                userLikeListVo.setMatchRate(Convert.toInt(score)); // 缘分值
            }

            userLikeListVos.add(userLikeListVo);
        }

        pageResult.setItems(userLikeListVos);

        return pageResult;
    }

    /**
     * 取消喜欢
     *
     * @param userId 取消喜欢对应的用户id
     * @return
     */
    public Boolean disLike(Long userId) {
        User user = UserThreadLocal.get();
        // 先判断是否是相互喜欢
        Boolean mutualLike = this.userLikeApi.isMutualLike(user.getId(), userId);

        // 取消喜欢
        Boolean result = this.userLikeApi.notLikeUser(user.getId(), userId);

        if (mutualLike && result) {
            // 取消好友关系，解除在环信平台的好友关系
            return this.imService.removeUser(userId);
        }
        return false;
    }

    /**
     * 关注粉丝
     *
     * @param userId 喜欢对应的用户id
     * @return
     */
    public Boolean likeFan(Long userId) {
        User user = UserThreadLocal.get();
        // 喜欢用户，如果用户是相互喜欢的话就会成为好友
        return this.userLikeApi.likeUser(user.getId(), userId);
    }

    /**
     * 修改用户个人信息
     *
     * @param userInfoVo 修改数据
     * @return
     */
    public Boolean updateUserInfo(UserInfoVo userInfoVo) {
        User user = UserThreadLocal.get();

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId()); // 用户id
        userInfo.setNickName(userInfoVo.getNickname()); // 昵称
        userInfo.setBirthday(userInfoVo.getBirthday()); // 年龄
        userInfo.setSex(StrUtil.equals(userInfoVo.getGender(), "man") ? SexEnum.MAN : SexEnum.WOMAN); // 性别
        userInfo.setCity(userInfoVo.getCity()); // 城市
        userInfo.setEdu(userInfoVo.getEducation()); // 学历
        userInfo.setIncome(userInfoVo.getIncome()); // 月收入
        userInfo.setIndustry(userInfoVo.getProfession()); // 行业
        userInfo.setMarriage(userInfoVo.getMarriage() == 0 ? "未婚" : "已婚"); // 婚姻情况

        return this.userInfoService.updateUserInfo(userInfo);
    }


    /**
     * 修改陌生人问题
     *
     * @param content 问题
     * @return
     */
    public Boolean updateQuestions(String content) {
        Long userId = UserThreadLocal.get().getId();
        return this.questionService.updateQuestions(userId, content);
    }


    /**
     * 通用设置查询
     *
     * @return
     */
    public SettingsVo querySettings() {
        try {
            SettingsVo settingsVo = new SettingsVo();
            User user = UserThreadLocal.get();
            // 封装数据
            settingsVo.setPhone(user.getMobile()); // 手机号

            // 根据用户id查询配置数据
            Settings settings = this.settingsService.findByUserId(user.getId());
            if (ObjectUtil.isEmpty(settings)) {
                /* 没查询到数据需要添加数据 */
                settings = new Settings();
                settings.setUserId(user.getId()); // 用户id
                settings.setLikeNotification(1);
                settings.setPinglunNotification(1);
                settings.setGonggaoNotification(1);

                Boolean result = this.settingsService.saveSettings(settings);
                if (!result) {
                    return null;
                }
            }

            // 封装数据
            settingsVo.setId(Integer.parseInt(settings.getId())); // 主键id
            settingsVo.setLikeNotification(settings.getLikeNotification() == 1); // 推送喜欢通知
            settingsVo.setPinglunNotification(settings.getPinglunNotification() == 1); // 推送评论通知
            settingsVo.setGonggaoNotification(settings.getGonggaoNotification() == 1); // 推送公告通知

            // 查询陌生人问题
            String question = this.tanHuaService.queryQuestion(user.getId());
            settingsVo.setStrangerQuestion(question); // 陌生人问题

            // 返回结果
            return settingsVo;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 设置/修改通用设置
     *
     * @param likeNotification    推送喜欢通知
     * @param pinglunNotification 推送评论通知
     * @param gonggaoNotification 推送公告通知
     * @return
     */
    public Boolean updateSettings(Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) {
        User user = UserThreadLocal.get();

        Settings settings = new Settings();
        settings.setUserId(user.getId()); // 用户id
        settings.setLikeNotification(likeNotification ? 1 : 0); // 推送喜欢通知
        settings.setPinglunNotification(pinglunNotification ? 1 : 0); // 推送评论通知
        settings.setGonggaoNotification(gonggaoNotification ? 1 : 0); // 推送公告通知

        return this.settingsService.updateSettings(settings);
    }


    /**
     * 查询黑名单列表
     * 分页
     *
     * @param page     当前页
     * @param pageSize 页大小
     * @return
     */
    public PageResult queryBlacklist(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        User user = UserThreadLocal.get();
        // 查询黑名单表
        IPage<BlackList> blackListIPage = this.blackListService.queryBlacklistPage(user.getId(), page, pageSize);
        List<BlackList> records = blackListIPage.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }

        // 获取黑名单表中的用户id集合
        List<Object> blackUserIdList = CollUtil.getFieldValues(records, "blackUserId");

        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(blackUserIdList);
        List<BlackListVo> blackListVoList = new ArrayList<>();
        BlackListVo blackListVo = null;

        for (UserInfo userInfo : userInfoList) {
            blackListVo = new BlackListVo();
            blackListVo.setId(userInfo.getUserId().intValue()); // 用户id
            blackListVo.setAvatar(userInfo.getLogo()); // 头像
            blackListVo.setNickname(userInfo.getNickName()); //昵称
            blackListVo.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman"); //性别
            blackListVo.setAge(userInfo.getAge()); // 年龄

            blackListVoList.add(blackListVo);
        }

        // 封装并返回
        pageResult.setItems(blackListVoList);
        return pageResult;
    }


    /**
     * 移除黑名单
     *
     * @param blackUserId 移除的黑名单用户id
     * @return Boolean
     */
    public Boolean deleteBlacklist(Long blackUserId) {
        return this.blackListService.deleteBlacklistByUserId(blackUserId);
    }
}